'use strict';

(() => {
  const video = document.querySelector('video');

  const getMediaStream = (stream) => {
    video.srcObject = stream;
  }

  const handleError = (error) => {
    console.log('error:', error);
  }

  const mediaStreamConstrains = {
    video: true,
    audio: true,
  }
  // 获取视频流喂给video标签
  navigator.mediaDevices.getUserMedia(mediaStreamConstrains).then(getMediaStream).catch(handleError);

  // 拍照（截图）
  const btn = document.getElementById('takePhoto');
  const picture = document.getElementById('picture');
  btn.addEventListener('click', e => {
    picture.width = 640;
    picture.height = 480;
    picture.getContext('2d').drawImage(video, 0, 0, picture.width, picture.height);
    // 创建下载按钮
    const downloadBtn = document.createElement('button');
    downloadBtn.id = 'download';
    downloadBtn.innerText = 'download';
    document.body.appendChild(downloadBtn);
    // 下载截图
    downloadBtn.addEventListener('click', e => {
      const picture = document.getElementById('picture');
      const a = document.createElement('a');
      a.download = 'photo'; // 设置下载文件名，默认是“下载”
      a.href = picture.toDataURL('image/png');
      a.click();
      a.remove();
    })
  })
  // 调滤镜
  const filter = document.getElementById('filter');
  filter.addEventListener('change', e => {
    picture.className = e.target.value;
  })
})()

